package com.zhainan.springmvc.utils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lvchang on 2016/10/2.
 */
public class ClassUtils {

    /**
     *
     * 根据包名定位到文件夹,然后根据读取该包下所有class文件,最后根据包名和文件名,构造返回的完整类名.
     * @param packageName
     * @return
     */
    public static List<String> getAllClassesFromPackage(String packageName){

        List<String> classNames = new ArrayList<String>();

        String pkg = "com.zhainan.springmvc.handler";
        String relPath = pkg.replace('.', '/');

        URL resource = Thread.currentThread().getContextClassLoader().getResource(relPath);
        if (resource == null) {
            throw new RuntimeException("Unexpected problem: No resource for "
                    + relPath);
        }

        File f = new File(resource.getPath());

        String[] files = f.list();

        for (int i = 0; i < files.length; i++) {

            String fileName = files[i];
            String className = null;
            String fileNm = null;

            if (fileName.endsWith(".class")) {

                fileNm = fileName.substring(0, fileName.length() - 6);
                className = pkg + '.' + fileNm;
            }
            if (className != null) {
                classNames.add(className);
            }
        }

        return classNames;
    }
}
